import React, { useState, useCallback } from "react";
import { Button, Card, Spin } from "antd";
import { FixedSizeList as ListComponent } from "react-window";

// 定义列表项的数据类型
interface Item {
  id: number;
  title: string;
  description: string;
}

// 定义组件的 props 类型
interface InfiniteScrollListProps {
  loadMore: (page: number) => Promise<Item[]>;
  initialData: Item[];
  itemHeight: number;
}

const InfiniteScrollList: React.FC<InfiniteScrollListProps> = ({
  loadMore,
  initialData,
  itemHeight,
}) => {
  const [data, setData] = useState<Item[]>(initialData);
  const [isLoading, setIsLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true); // 是否还有更多数据

  // 加载更多数据
  const handleLoadMore = useCallback(async () => {
    if (isLoading || !hasMore) return;
    setIsLoading(true);
    try {
      const newData = await loadMore(page + 1);
      if (newData.length === 0) {
        setHasMore(false); // 没有更多数据
      } else {
        setData((prevData) => [...prevData, ...newData]);
        setPage((prevPage) => prevPage + 1);
      }
    } finally {
      setIsLoading(false);
    }
  }, [isLoading, hasMore, loadMore, page]);

  // 渲染列表项
  const Row = ({
    index,
    style,
  }: {
    index: number;
    style: React.CSSProperties;
  }) => {
    if (index >= data.length) {
      return (
        <div style={style} className="flex justify-center items-center">
          <Spin />
        </div>
      );
    }
    const item = data[index];
    return (
      <div style={style} className="p-2">
        <Card
          bordered
          hoverable={true}
          title={item.title}
          className="shadow-md hover:shadow-lg transition-shadow "
        >
          <p className="text-gray-700 h-30">
            {item.description}{" "}
            <Button type="primary" className="mt-1">
              操作
            </Button>
          </p>
        </Card>
      </div>
    );
  };

  // 监听渲染的列表项，判断是否需要加载更多
  const handleItemsRendered = ({
    visibleStopIndex,
  }: {
    visibleStopIndex: number;
  }) => {
    if (visibleStopIndex >= data.length - 1 && !isLoading && hasMore) {
      handleLoadMore();
    }
  };

  return (
    <ListComponent
      height={800}
      itemCount={data.length + (hasMore ? 1 : 0)} // 如果有更多数据，增加一个占位符
      itemSize={itemHeight}
      width="100%"
      onItemsRendered={handleItemsRendered} // 使用 react-window 提供的回调
    >
      {({ index, style }) => <Row index={index} style={style} />}
    </ListComponent>
  );
};

export default InfiniteScrollList;
